import axios from "axios"
import { getLocalStorage, safeGet, getSessionStorage } from "@/common.js"
import { decrypt, removeTokenSign, resolveParams, processError, startPost, endPost } from "./tools.js" 
export const isDebug = process.env.VUE_APP_ENV == 'development' // 是否开启debug
export const baseURL = isDebug ? process.env.VUE_APP_BASE_URL : `${window.location.protocol}//${window.location.host}/open/`
/************配置axios****** */
export const baseService = (url = '', timeout = 10e3) => axios.create({ baseURL: url, timeout })
let service = baseService(baseURL)
/*设置请求拦截器*/
service.interceptors.request.use(
  config => {
    config.headers['Authorization'] = getSessionStorage('token') || '100.ac75144c231b4105a7f2dc8cccc0ea23'
    config.headers['token'] = getSessionStorage('token') || '100.ac75144c231b4105a7f2dc8cccc0ea23'
    config.headers["Content-Type"] = isDebug ? 'application/x-www-form-urlencoded' : "application/x-www-form-urlencoded" // application/json
    return config
  },
  err => Promise.reject(err)
)
/*响应拦截器*/
service.interceptors.response.use(
  res => {
    if ((!isDebug) && !(res.data instanceof Blob)) { res.data = safeGet(() => res.data.errcode, '') ? res.data : JSON.parse(decrypt(res.data)) } // 加密模式 && 不是文件流请求
    return res.data.errcode ? res.data : res
  },
  err => {
    if(!err.response) { return Promise.reject(window.navigator.onLine ? err : '你的网络连接有问题')} // 服务器结果都没返回（可能服务器崩了，或者断网了)
    if(String(err.response.status).includes('40')) { removeTokenSign() }
  }
)
/**************************************************************************************************** */
/******************************************分******************************************************** */
/******************************************割******************************************************** */
/******************************************线******************************************************** */
/**************************************************************************************************** */
/**
 * 封装一个request请求
 * @param {*} options 
 * @returns 
 * const res = await request({
 *   url: '/api/userInfo',
 *   header: {},
 *   data: { name: '张三', age: 18 },
 *   responseType: 'blob'
 * })
 */
export const request = function (options) {
  return new Promise((resolve, reject) => service.request({ method: "GET", url: '', data: {}, ...options }).then(res => processError(res, options.url, options.type, resolve, reject)))
}
/**
 * 封装一个post请求
 * @param {String} url 请求的url地址
 * @param {Object} params 请求参数
 * @param {*} defaultVal 接口请求的mock数据
 * @param {*} type 返回数据类型  1代表只返回data    0代表不做任何处理直接返回格式：{code:xx, data:xx, msg:xx}
 * @returns 
 * @举例 const res = await this.$post('/apprepair/editRepair', {id:1, name:'zz'})
 */
export const post = function (url, params, type = 1) {
  return new Promise((resolve, reject) => service.post(url, resolveParams(params)).then(res => processError(res, url, type, resolve, reject)))
}
/**
 * mock数据
 * @param {String} url 请求的url地址
 * @param {Object} params 请求参数
 * @param {*} defaultVal 接口请求的mock数据
 * @returns 
 * @举例 const res = await this.$mock('/api/userInfo', {id: '1'}, {name: '张三', age: 18})  ---->  {name: '张三', age: 18}
 */
export const mock = (url, params, defaultVal) => new Promise(async resolve => setTimeout(() => resolve(defaultVal), 600))
// 注册到全局vue
export default {
  install(Vue) {
    Vue.prototype.$request = request
    Vue.prototype.$mock = mock
    Vue.prototype.$post = post
    Vue.prototype.$startPost = startPost
    Vue.prototype.$endPost = endPost
  }
}